<template>
  <basic-container>
    <avue-crud
      ref="crud"
      v-model="form"
      :option="option"
      :table-loading="loading"
      :data="data"
      :page="page"
      :before-open="beforeOpen"
      @row-update="rowUpdate"
      @row-save="rowSave"
      @row-del="rowDel"
      @row-click="rowClick"
      @refresh-change="refresh"
      @search-change="searchChange"
      @search-reset="searchReset"
      @selection-change="selectionChange"
      @current-change="currentChange"
      @size-change="sizeChange"
      @on-load="onLoad"
    >
      <template slot="dataMenuForm">
        <el-tree
          ref="tree"
          :disabled="dataMenuDisabled"
          :default-checked-keys="checkedMenuKeys"
          :props="dataMenuProps"
          :data="dataManus"
          show-checkbox
          node-key="id"
        />
      </template>
      <template slot="dataScopeForm" slot-scope="{row}">
        <el-select v-model="row.dataScope" default-first-option @change="onChangeDataScopeOption">
          <el-option v-for="item in dataScope" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </template>
      <template
        slot="status"
        slot-scope="{row}"
      >
        <el-tag :type="row.status? 'success':'danger'">
          {{ row.status? '启用': '禁用' }}
        </el-tag>
      </template>
    </avue-crud>
  </basic-container>
</template>

<script>
import { mapGetters } from 'vuex'
import { isAlphabets } from '@/util/ValidateUtil'

const addSysRoleAction = 'sys/role/addSysRole'
const updateSysRoleAction = 'sys/role/updateSysRole'
const removeSysRoleAction = 'sys/role/removeSysRole'
const removeSysRolesAction = 'sys/role/removeSysRoles'
const getSysRoleByIdAction = 'sys/role/getSysRoleById'
const getSysRolePageListAction = 'sys/role/getSysRolePageList'

const getSysRoleMenuListAction = 'sys/menu/getSysMenuList'
const getSysRoleMenuByRoleIdAction = 'sys/menu/listSidebarMenuByRoleId'

export default {
  name: '',
  data () {
    const validateRoleCode = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('角色标识码不能为空'))
      }
      if (!isAlphabets(value)) {
        callback(new Error('角色标识码只能是字母或者拼音!'))
      } else {
        callback()
      }
    }
    const statusDic = [
      {
        label: '启用',
        value: true
      },
      {
        label: '禁用',
        value: false
      }
    ]
    return {
      dataManus: [],
      dataMenuProps: {
        label: 'menuName',
        value: 'id',
        children: 'children'
      },
      checkedMenuKeys: [],
      dataMenuDisabled: false,
      form: {},
      query: {},
      loading: true,
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0
      },
      selectionList: [],
      option: {
        // title: '角色信息表',
        border: true,
        menu: true,
        lazy: true,
        tip: true,
        tipPlacement: 'top-start',
        index: true,
        indexLabel: '序号',
        indexFixed: true,
        selection: true,
        selectionWidth: 60,
        selectionFixed: false,
        expand: false,
        defaultExpandAll: true,
        checkStrictly: true,
        addBtn: true,
        viewBtn: true,
        excelBtn: false,
        printBtn: false,
        dialogDrag: true,
        dialogDirection: 'rtl',
        dialogType: 'dialog',
        column: [
          {
            label: '角色名称',
            prop: 'roleName',
            type: 'input',
            hide: false,
            showWordLimit: true,
            maxlength: 30,
            showColumn: true,
            overHidden: true,
            addDisplay: true,
            editDisplay: true,
            viewDisplay: true,
            rules: [{
              required: true,
              message: '请输入角色名称',
              trigger: 'blur'
            }]
          },
          {
            label: '角色标识',
            prop: 'roleCode',
            type: 'input',
            hide: false,
            showWordLimit: true,
            maxlength: 60,
            showColumn: true,
            overHidden: true,
            addDisplay: true,
            editDisplay: true,
            viewDisplay: true,
            rules: [{
              required: true,
              validator: validateRoleCode,
              trigger: 'blur'
            }]
          },
          {
            label: '显示顺序',
            prop: 'roleOrder',
            type: 'number',
            gutter: 24,
            hide: false,
            showColumn: false,
            overHidden: true,
            addDisplay: true,
            editDisplay: true,
            viewDisplay: true,
            rules: [{
              required: false,
              message: '请输入显示顺序',
              trigger: 'blur'
            }],
            value: 1
          },
          {
            label: '菜单权限',
            prop: 'dataMenu',
            type: 'tree',
            gutter: 100,
            hide: true,
            formslot: true,
            showColumn: false,
            multiple: true,
            addDisplay: true,
            editDisplay: true,
            viewDisplay: true,
            rules: [{
              required: false,
              message: '菜单权限不能为空',
              trigger: 'blur'
            }],
            dicData: [],
            props: {
              label: 'menuName',
              value: 'id',
              children: 'children'
            }
          },
          // {
          //   label: '数据权限',
          //   prop: 'dataScope',
          //   type: 'select',
          //   hidden: true,
          //   formslot: true,
          //   showColumn: true,
          //   overHidden: true,
          //   addDisplay: false,
          //   editDisplay: false,
          //   viewDisplay: false,
          //   rules: [{
          //     required: true,
          //     message: '请输入数据范围（1：全部数据权限 2：自定数据权限 3：本部门数据权限 4：本部门及以下数据权限）',
          //     trigger: 'blur'
          //   }],
          //   dictData: []
          // },
          {
            label: '状态',
            prop: 'status',
            type: 'switch',
            span: 24,
            slot: true,
            showColumn: false,
            overHidden: true,
            addDisplay: true,
            editDisplay: true,
            viewDisplay: true,
            dicData: statusDic,
            value: true
          },
          {
            label: '备注',
            prop: 'remark',
            type: 'textarea',
            hide: true,
            showColumn: false,
            showWordLimit: true,
            maxlength: 500,
            span: 24
          }
        ]
      },
      data: [],
      dataScope: [
        {
          label: '全部数据权限',
          value: 1
        },
        {
          label: '本部门数据权限',
          value: 2
        },
        {
          label: '本部门及以下数据权限',
          value: 3
        },
        {
          label: '仅本人数据权限',
          value: 4
        },
        {
          label: '自定数据权限',
          value: 5
        }
      ]
    }
  },
  computed: {
    ...mapGetters(['permissions', 'website']),
    ids () {
      const ids = []
      this.selectionList.forEach((e) => {
        ids.push(e.id)
      })
      return ids
    }
  },
  mounted () {
    this.fetchMenus()
  },
  methods: {
    // 所有菜单节点数据
    getMenuAllCheckedKeys () {
      // 目前被选中的菜单节点
      const checkedKeys = this.$refs.tree.getCheckedKeys()
      // 半选中的菜单节点
      // const halfCheckedKeys = this.$refs.tree.getCheckedKeys()
      // checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys)
      return checkedKeys
    },
    onChangeDataScopeOption (data) {
      console.log(data)
    },
    rowSave (row, loading, done) {
      this.loading = true
      loading()
      const saveData = Object.assign(row, { dataMenu: this.getMenuAllCheckedKeys() })
      this.$store.dispatch(addSysRoleAction, saveData).then((res) => {
        this.loading = false
        done()
        const resCode = res.code
        const errorMsg = res.message
        if (resCode === 0) {
          this.onLoad(this.page)
          this.$message({
            type: 'success',
            message: '保存操作成功!'
          })
        } else {
          this.$message({
            type: 'error',
            showClose: true,
            message: errorMsg || '保存数据失败,请稍后再试!'
          })
        }
      }, (error) => {
        this.loading = false
        done()
        console.log(error)
      })
    },
    rowUpdate (row, index, loading, done) {
      this.loading = true
      loading()
      const updateData = Object.assign(row, { dataMenu: this.getMenuAllCheckedKeys() })
      this.$store.dispatch(updateSysRoleAction, updateData).then((res) => {
        this.loading = false
        done()
        const resCode = res.code
        const errorMsg = res.message
        if (resCode === 0) {
          this.onLoad(this.page)
          this.$message({
            type: 'success',
            message: '编辑操作成功!'
          })
        } else {
          this.$message({
            type: 'error',
            showClose: true,
            message: errorMsg || '编辑数据失败,请稍后再试!'
          })
        }
      }, (error) => {
        this.loading = false
        done()
        console.log(error)
      })
    },
    rowDel (row) {
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.loading = true
          const idParams = { id: row.id }
          return this.$store.dispatch(removeSysRoleAction, idParams)
        })
        .then((res) => {
          this.loading = false
          const resCode = res.code
          const errorMsg = res.message
          if (resCode === 0) {
            this.onLoad(this.page)
            this.$message({
              type: 'success',
              message: '删除操作成功!'
            })
          } else {
            this.loading = false
            this.$message({
              type: 'error',
              showClose: true,
              message: errorMsg || '删除数据失败,请稍后再试!'
            })
          }
        }).catch(() => {

        })
    },
    handleDelete () {
      if (this.selectionList.length === 0) {
        this.$message.warning('请选择至少一条数据')
        return
      }
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.loading = true
          const idParams = { ids: this.ids }
          return this.$store.dispatch(removeSysRolesAction, idParams)
        })
        .then((res) => {
          this.loading = false
          const resCode = res.code
          const errorMsg = res.message
          if (resCode === 0) {
            this.$message({
              type: 'success',
              message: '批量删除操作成功!'
            })
            this.onLoad(this.page)
            this.$refs.crud.toggleSelection()
          } else {
            this.loading = false
            this.$message({
              type: 'error',
              showClose: true,
              message: errorMsg || '批量删除数据失败,请稍后再试!'
            })
          }
        }).catch(() => {

        })
    },
    rowClick (row, event, column) {
      this.$refs.crud.rowView(row, column)
    },
    refresh ({ page, searchForm }) {
      this.onLoad(page)
    },
    beforeOpen (done, type) {
      if (type === 'view') {
        this.dataMenuDisabled = true
      } else {
        this.dataMenuDisabled = false
      }
      if (['edit', 'view'].includes(type)) {
        const idParams = { id: this.form.id }
        this.$store.dispatch(getSysRoleByIdAction, idParams).then((res) => {
          const resCode = res.code
          const errorMsg = res.message
          if (resCode === 0) {
            this.form = res.data
            // 查询对应的菜单列表
            this.fetchRoleMenuByRoleCode(idParams)
          } else {
            this.$message({
              type: 'error',
              showClose: true,
              message: errorMsg || '查询数据失败,请稍后再试!'
            })
          }
        }).catch((err) => {
          console.log(err)
          this.$message({
            type: 'error',
            showClose: true,
            message: '查询数据异常,请稍后再试!'
          })
        })
      }
      done()
    },
    searchReset () {
      this.query = {}
      this.onLoad(this.page)
    },
    searchChange (params, done) {
      done()
      this.query = params
      this.page.currentPage = 1
      this.onLoad(this.page, params)
    },
    selectionChange (list) {
      this.selectionList = list
    },
    selectionClear () {
      this.selectionList = []
      this.$refs.crud.toggleSelection()
    },
    currentChange (currentPage) {
      this.page.currentPage = currentPage
    },
    sizeChange (pageSize) {
      this.page.pageSize = pageSize
    },
    onLoad (page, params = {}) {
      this.loading = true
      let queryData = {
        pageNo: page.currentPage,
        pageSize: page.pageSize
      }
      queryData = Object.assign(queryData, Object.assign(params, this.query))
      this.$store.dispatch(getSysRolePageListAction, queryData).then((res) => {
        this.loading = false
        const resCode = res.code
        const errorMsg = res.message
        if (resCode === 0) {
          const data = res.data
          this.page.total = parseInt(data.total)
          this.data = data.records
          this.selectionClear()
        } else {
          this.$message({
            type: 'error',
            showClose: true,
            message: errorMsg || '查询数据失败,请稍后再试!'
          })
        }
      }).catch((err) => {
        console.log(err)
        this.$message({
          type: 'error',
          showClose: true,
          message: '查询数据异常,请稍后再试!'
        })
      })
    },
    fetchMenus () {
      // 获取对应的树结构数据
      this.$store.dispatch(getSysRoleMenuListAction, { filterButtonPermission: false }).then((res) => {
        const resCode = res.code
        const errorMsg = res.message
        if (resCode === 0) {
          const index = this.$refs.crud.findColumnIndex('dataMenu')
          this.option.column[index].dicData = res.data
          this.dataManus = res.data
        } else {
          this.$message({
            type: 'error',
            showClose: true,
            message: errorMsg || '查询数据异常,请稍后再试!'
          })
        }
      }).catch((err) => {
        console.log(err)
        this.$message({
          type: 'error',
          showClose: true,
          message: '查询菜单数据异常,请稍后再试!'
        })
      })
    },
    fetchRoleMenuByRoleCode (data) {
      this.$store.dispatch(getSysRoleMenuByRoleIdAction, data).then((res) => {
        const menuData = res.data
        const menuIds = menuData.map((r) => {
          return r.id
        })
        if (menuIds && menuIds.length === 1 && menuIds[0] === -1) {
          // this.$set(this.form, 'dataMenu', null)
          this.checkedMenuKeys = null
        } else {
          // this.$set(this.form, 'dataMenu', menuIds)
          this.checkedMenuKeys = menuIds
        }
      })
    }
  },
  head () {
    return {
      title: '角色管理 | ' + this.website.name,
      meta: [
        { hid: 'description', name: 'description', content: '角色管理' }
      ]
    }
  }
}
</script>

<style>
</style>
